package com.alibaba.dubbo.remoting.msgcodec;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;

import com.alibaba.dubbo.common.configure.ExtensionConfiguratorUtils;
import com.alibaba.dubbo.remoting.MessageEncode;

public class RSAEncode extends RSACodec implements MessageEncode {
	private RSAPublicKey publicKey;

	public RSAPublicKey getPublicKey() {
		return publicKey;
	}

	public void setPublicKey(RSAPublicKey publicKey) {
		this.publicKey = publicKey;
	}

	public RSAEncode(){
		ExtensionConfiguratorUtils instance = ExtensionConfiguratorUtils.getInstance();
		String name = ExtensionConfiguratorUtils.combine(RSAEncode.class, "publicKey");
		Object value = instance.getValue(name);
		if(value == null){
			try {
				publicKey = (RSAPublicKey) getPublicKeyWithBase64(
						"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCPOkHi+/1FPk+UaV4NeUQ4Tk1NCwfyBQXRb8Mt"
						+ "extlJvvuIwC/HsCFOwSBbHeiCrvLGANP8i3kKEPWcogToVr0Kr6deO7Nhrm2pz0BW+3spz03JJEs"
						+ "L9WsG6MRcl4FmChIsLHZfBqYJTJxS7ZxfYgHN5zn7jH3IuR6HJH+BI/76QIDAQAB");
			} catch (Exception e) {
				throw new IllegalArgumentException(e);
			}
		}else if(value instanceof byte[]){
			try {
				publicKey = (RSAPublicKey)getPublicKey((byte[])value);
			} catch (Exception e) {
				throw new IllegalArgumentException(e);
			}
		}else {
			try {
				publicKey = (RSAPublicKey) getPublicKeyWithBase64(value.toString());
			} catch (Exception e) {
				throw new IllegalArgumentException(e);
			}
		}
	}

	@Override
	public int encode(InputStream in, OutputStream out/*,
			MessageEncodeRegistry registry*/) throws IOException {
		try {
			int ret = encrypt(in, out, publicKey);
			//registry.appendEncode("rsa");
			return ret;
		} catch (Exception e) {
			throw new IOException(e);
		}
	}
}
